﻿using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using Uber.Core.Model;
using Uber.WebUI.Models;

namespace Uber.WebUI.Controllers
{
    [Authorize]
    public class ProfileController : Controller
    {
        protected string GetGravatarUrl(string email)
        {
            if (string.IsNullOrWhiteSpace(email)) return null;

            var hash = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(email.Trim(), "MD5");
            if (hash != null) hash = hash.Trim().ToLower();

            var gravatarUrl = string.Format("http://www.gravatar.com/avatar/{0}?rating=G&s=200&d=identicon", hash);
            return gravatarUrl;
        }

        public ActionResult Index()
        {
            var a = Fa.Account.Get(Gl.UserId());
            return View(new ProfileDisplay
                            {
                                DisplayName = a.DisplayName,
                                Email = a.Email,
                                PicUrl = GetGravatarUrl(a.Email),
                                IsAweOid = a.IsAweOid
                            });
        }

        public ActionResult Edit()
        {
            var a = Fa.Account.Get(Gl.UserId());
            return View(new ProfileEditInput { DisplayName = a.DisplayName, Email = a.Email, Aemail = a.Aemail });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(ProfileEditInput input)
        {
            if (!ModelState.IsValid) return View(input);
            Fa.Account.EditProfile(Gl.UserId(), input.Aemail, input.DisplayName);
            return RedirectToAction("index");
        }

        public ActionResult MyPurchases()
        {
            var userId = Gl.UserId();
            var items = Fa.U.GetAll<Purchase>().Where(o => o.UserId == userId);
            return View(items);
        }

        [HttpPost]
        public ActionResult Download(long id)
        {
            var o = Fa.U.Get<ProductVersion>(id);
            var f = Fa.Storage + o.FileName;
            return File(f, "application/octet-stream",o.FileName);
        }
    }
}